<template>
  <div class="draw-guess-container">
    <div class="table-list">
      <div class="list">
        <el-row :gutter="8">
          <el-col v-for="item in list.items" :span="4" :key="item.id">
            <div class="guess-item">
              <el-image
                :src="item.url || item.base64"
                :preview-src-list="[item.url || item.base64]"
                fit="contain"
                class="img"
                lazy
              >
                <div slot="error" class="image-slot">
                  暂无图片
                </div>
              </el-image>
              <div class="footer">
                <el-checkbox :value="checkIds.includes(item.id)" class="mr-10" @change="(e) => {handleCheck(e, item)}" />
                <div class="footer-item" @click="handleCheck(e, item)">{{ item.word }}</div>
                <div class="button-text" @click="deleteItem(item)">删除</div>
              </div>
              <div :class="item.url ? 'status-green' : 'status-red'" class="status-indicator"/>
            </div>
          </el-col>
        </el-row>
      </div>
      <div class="page-list">
        <div class="select-container">
          <div class="select">已选：{{ checkIds.length }}条</div>
          <div class="select button-text" @click="toSelect(true)">全选</div>
          <div class="select button-text" @click="toSelect(false)">全不选</div>
          <div class="select button-text" @click="batchDelete()">批量删除</div>
        </div>
        <el-pagination
          :current-page="page"
          :page-sizes="[60, 100, 200, 300, 400]"
          :page-size="perPage"
          :total="list.total"
          background
          layout="prev, pager, next, jumper,total, sizes"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"/>
      </div>
    </div>
    <canvas ref="canvas" style="display:none;"/>
  </div>
</template>
<script>
import { getDrawData, deleteImg } from './utils/request';
export default {
  components: { },
  mixins: [],
  data() {
    return {
      page: 1,
      perPage: 60,
      list: {
        items: [],
        total: 0,
        isInit: true
      },
      checkIds: []
    };
  },
  computed: {

  },
  created() {
    this.getDrawData();
  },
  methods: {
    async getDrawData(reset) {
      if (reset) {
        this.page = 1;
      }
      const data = {
        page: this.page,
        perPage: this.perPage
      };
      const res = await getDrawData(data);
      this.list = res.data;
      this.generateImages();
      console.log(res);
    },
    deleteItem(item) {
      this.$confirm('是否确定删除该图？', '', {
        confirmButtonText: '确定',
        type: 'warning',
        showClose: false,
        center: true,
        iconClass: 'charge-icon',
        customClass: 'del-message del-message-cancel'
      }).then(() => {
        deleteImg({ ids: item.id }).then(res => {
          if (res.code === 200) {
            // this.data.drawData = this.data.drawData.filter((i) => !this.data.ids.includes(i.id.toString()));
            this.getDrawData();
            // this.getDrawData(true);
            this.$message.success('删除成功');
          } else {
            this.$message.error(res.message);
          }
        });
      });
    },
    batchDelete() {
      if (this.checkIds.length === 0) {
        this.$message.success('请选择需要删除的图片');
        return;
      }
      this.$confirm('是否确定批量删除？', '', {
        confirmButtonText: '确定',
        type: 'warning',
        showClose: false,
        center: true,
        iconClass: 'charge-icon',
        customClass: 'del-message del-message-cancel'
      }).then(() => {
        deleteImg({ ids: this.checkIds.join(',') }).then(res => {
          if (res.code === 200) {
            // this.data.drawData = this.data.drawData.filter((i) => !this.data.ids.includes(i.id.toString()));
            this.getDrawData();
            // this.getDrawData(true);
            this.$message.success('删除成功');
          } else {
            this.$message.error(res.message);
          }
        });
      });
    },
    toSelect(isAll) {
      if (isAll) {
        if (this.list.items.length) {
          this.list.items.forEach(i => {
            if (!this.checkIds.includes(i.id)) {
              this.checkIds.push(i.id);
            }
          });
        }
      } else {
        this.checkIds = [];
      }
    },
    handleCheck(e, item) {
      console.log(e, item);
      if (this.checkIds.includes(item.id)) {
        this.checkIds = this.checkIds.filter(i => i !== item.id);
      } else {
        this.checkIds.push(item.id);
      }
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.getDrawData(true);
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
      this.getDrawData();
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },
    generateImages() {
      if (!this.list || !this.list.items) return;
      this.list.items.forEach((example, index) => {
        if (example.url) return; // 有图片的无需重新绘制
        const drawInfo = JSON.parse(example.drawInfo);
        const canvas = this.$refs.canvas;
        const ctx = canvas.getContext('2d');

        // 清空 canvas
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        // 设置 canvas 尺寸
        canvas.width = 750;
        canvas.height = Math.max(...drawInfo.map(line => Math.max(...line.points.map(point => point[1])))) + 20;

        // 填充白色背景
        ctx.fillStyle = '#FFFFFF'; // 设置填充颜色为白色
        ctx.fillRect(0, 0, canvas.width, canvas.height); // 绘制填充矩形

        // 绘制每个点
        drawInfo.forEach(line => {
          ctx.strokeStyle = line.strokeStyle;
          ctx.lineWidth = line.lineWidth;

          ctx.beginPath();
          line.points.forEach((point, i) => {
            const [x, y] = point;
            if (i === 0) {
              ctx.moveTo(x, y);
            } else {
              ctx.lineTo(x, y);
            }
          });
          ctx.stroke();
        });

        // 将 Canvas 内容转换为 Base64 图片
        const dataURL = canvas.toDataURL();
        example.base64 = dataURL;
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.draw-guess-container {
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
  height: 100vh;
  .table-list {
    display: flex;
    flex-direction: column;
    height: 0;
    flex: 1;
    .list {
      @include scrollBar($x: hidden, $y: auto, $width: 6px);
      height: 0;
      flex: 1;
      padding: 16px;
    }
  }
  .guess-item {
    position: relative;
    border-radius: 8px;
    background-color: #fff;
    overflow: hidden;
    margin-bottom: 8px;
    &::v-deep {
      .el-image {
        width: 100%;
        height: 150px;
      }
      .image-slot {
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 14px;
        background-color: #e5e5e5;
        width: 100%;
        height: 100%;
      }
      .status-indicator {
        position: absolute;
        width: 10px;
        height: 10px;
        border-radius: 50%; /* If you want circular indicators */
      }

      .status-red {
        top: 5px;
        right: 5px; /* Offset to avoid overlap */
        background-color: red; /* Change colors based on your requirements */
      }

      .status-green {
        top: 5px;
        right: 5px; /* Top and right position adjustments */
        background-color: green; /* Change colors based on your requirements */
      }
    }
  }
  .footer {
    padding: 5px 10px;
    display: flex;
    align-items: center;
    .footer-item {
      font-size: 14px;
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
      flex: 1;
      cursor: pointer;
    }
  }
}
.page-list {
  padding: 0 16px 0 16px;
  display: flex;
  align-items: center;
  margin-right: 10px;
}
.select-container {
  display: flex;
  align-items: center;
  .select {
    margin-right: 10px;
  }
}
.mr-10 {
  margin-right: 10px
}
</style>
